import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms';
import { Params } from '@angular/router';
import { AfMessageService, AfNavigationService, AfDateService } from '@core';
import { differenceInCalendarDays } from 'date-fns';
import { NzMessageService } from 'ng-zorro-antd/message';
import { TransferItem } from 'ng-zorro-antd/transfer';
import { lastValueFrom, zip } from 'rxjs';
import { SecurityService } from 'src/app/routes/security/security.service';

import { CodeGenService } from '../../../codegen.service';

@Component({
  selector: 'app-security-user-edit',
  styleUrls: ['./edit.component.less'],
  templateUrl: './edit.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MetaWorkspaceEditComponent implements OnInit {
  form!: UntypedFormGroup;
  submitting = false;
  saveError = null;

  constructor(
    private fb: UntypedFormBuilder,
    private msg: NzMessageService,
    private cdr: ChangeDetectorRef,
    private msgSrv: AfMessageService,
    private navSrv: AfNavigationService,
    private dateSrv: AfDateService,
    private cgSrv: CodeGenService,
    private securitySrv: SecurityService
  ) {
    // this.queryWorkspaceUser(11);
  }

  editParam!: Params;
  record: any;
  btn: any = 'add';
  ngOnInit(): void {
    this.form = this.fb.group({
      id: ['', []],
      name: ['', [Validators.required]],
      label: ['', [Validators.required]]
    });

    this.initFormValue();
    this.queryWorkspaceUser(this.form.controls['id'].value);
  }

  selectedIndex = 0;
  treeTitle: any = '权限';
  initFormValue() {
    this.editParam = this.navSrv.getQueryParam();
    this.btn = this.editParam['btn'];
    this.selectedIndex = this.editParam['index'];
    if (this.btn == 'edit') {
      this.record = JSON.parse(this.editParam['record']);
      // console.log(JSON.stringify(this.record));
      this.treeTitle = `为“${this.record.name}权限`;
      this.form.patchValue(this.record);
    }
  }

  submit(): void {
    const body = this.form.getRawValue();

    this.submitting = true;
    this.cgSrv.saveWorkspace(body).subscribe(res => {
      if (res.status) {
        this.form.controls['id'].setValue(res.data);
        this.treeTitle = `为“${this.form.controls['name'].value}”分配角色`;

        this.msgSrv.msg_success(`提交成功`);
        this.back();
      } else {
        this.msgSrv.msg_warning(`${res.msg}`);
      }
    });

    setTimeout(() => {
      this.submitting = false;
      this.cdr.detectChanges();
    }, 100);
  }

  today = new Date();
  disabledDate = (current: Date): boolean => {
    return differenceInCalendarDays(current, this.today) < 0;
  };

  back() {
    this.navSrv.navigateByUrl('/codegen/meta/workspace/list');
  }

  translist: TransferItem[] = [];
  queryWorkspaceUser(wsId: any) {
    this.translist = [];
    zip(this.cgSrv.queryWorkspaceUser(wsId), this.securitySrv.queryUser({ username: '', nickname: '', pi: 0, ps: 10000 })).subscribe(
      ([res1, res2]: [any, any]) => {
        // 需要初始化为[],否则页面不显示

        this.translist = [];
        if (res1 && res1.length >= 1) {
          res1.forEach((item: any) => {
            this.translist.push({
              title: `${item.username}`,
              disabled: item.disabled,
              direction: 'right'
            });
          });
        }

        const users: any[] = res2.list;
        if (users.length >= 1) {
          users.map(item => {
            this.translist.push({
              id: item.id,
              title: item.username,
              disabled: false,
              direction: 'left'
            });
          });
        }
        this.cdr.detectChanges();
      }
    );
  }

  grantUser() {
    if (this.form.controls['id'].value == null || this.form.controls['id'].value == '') {
      this.msgSrv.msg_error('请先提交工作空间用户后，才能提交权限');
      return;
    }
    const selectItem: TransferItem[] = this.translist.filter(item => item.direction == 'right');
    console.log('grantUser', selectItem);
    if (!selectItem || selectItem.length <= 0) {
      this.msgSrv.msg_error('请选择用户');
      return;
    }
    const roleIds = selectItem.map((item: any) => item.title);

    this.cgSrv.saveWorkspaceUser(this.record.id, roleIds).subscribe(res => {
      if (res.status) {
        this.msgSrv.msg_success('用户分配成功');
        this.back();
      } else {
        this.msgSrv.msg_error(res.msg);
      }
    });
  }
}
